package main

import (
	"fmt"
	"sync"
	"time"
)

/*
读写锁
*/
func main() {
	go func() {
		for i := 0; i < 5; i++ {
			d7_deposit(200, "aaa")
		}
	}()

	go func() {
		for i := 0; i < 5; i++ {
			fmt.Println("查看余额：", d7_balance())
		}
	}()

	var input string
	fmt.Scanln(&input)
}

// 账号
var (
	// 使用读写锁，防止造成死锁
	d7Lock sync.RWMutex
	//一个只能为1和0的信号量叫做二元信号量(binary semaphore)
	d7Balance int
)

// 存钱，内部调用查询余额，造成死锁
func d7_deposit(amount int, name string) {
	d7Lock.Lock()
	defer d7Lock.Unlock()
	fmt.Println("存钱->begin, name=", name)
	time.Sleep(1 * time.Second)
	d7Balance += amount
	fmt.Println("存钱->end, name=", name)
}

// 查询余额
func d7_balance() int {
	d7Lock.RLock()
	defer d7Lock.RUnlock()

	b := d7Balance
	return b
}
